﻿
using Utility.Helpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Utility.Helpers;

namespace Utility.Encryption
{
    public static class EncryptHelper
    {
        /// <summary>
        /// url加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string EncryptWithUrlEncode(this string source, string key = "")
        {
            if (string.IsNullOrEmpty(source))
                return "";
            if (string.IsNullOrEmpty(key))
            {
                return HttpUtility.UrlEncode(Encrypt.DesEncrypt(source));
            }
            return HttpUtility.UrlEncode(Encrypt.DesEncrypt(source, key));
        }

        /// <summary>
        /// 将参数解密并转成对应的数据类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T DecryptWithUrlDecode<T>(this string source, string key = "")
        {
            if (string.IsNullOrEmpty(source))
            {
                return default ;
            }
            try
            {
                var decodeStr = string.IsNullOrEmpty(key) ? Encrypt.DesDecrypt(HttpUtility.UrlDecode(source).Replace(" ", "+")) : Encrypt.DesDecrypt(HttpUtility.UrlDecode(source).Replace(" ", "+"), key);
                if (string.IsNullOrEmpty(decodeStr))
                {
                    return default;
                }
                return (T)System.Convert.ChangeType(decodeStr, typeof(T));
            }
            catch (Exception)
            {
                return default;
            }
        }
    }

}
